#!/bin/bash
HOST_IP=${HOST_IP:-"127.0.0.1"}
TOP_DIR=${TOP_DIR:-/opt/stack/devstack}
FILES=$TOP_DIR/files
ADMIN_USER=${ADMIN_USRE:-admin}
ADMIN_TENANT=${ADMIN_TENANT:-admin}
ADMIN_PASSWORD=${ADMIN_PASSWORD:-hezudaopp}
IMAGE_FNAME=${IMAGE_FNAME:-tty.tgz}
GLANCE_HOSTPORT=${GLANCE_HOSTPORT:-172.16.100.55:9292}

# Import common functions
source $TOP_DIR/functions

# Create a directory for the downloaded image tarballs.
if [ ! -d "$FILES/images"]; then 
	mkdir -p $FILES/images 
fi

set -o xtrace

TOKEN=`curl -s -d  "{\"auth\":{\"passwordCredentials\": {\"username\": \"$ADMIN_USER\", \"password\": \"$ADMIN_PASSWORD\"}, \"tenantName\": \"$ADMIN_TENANT\"}}" -H "Content-type: application/json" http://$HOST_IP:5000/v2.0/tokens | python -c "import sys; import json; tok = json.loads(sys.stdin.read()); print tok['access']['token']['id'];"`
if [ ! -f $FILES/$IMAGE_FNAME ]; then
    echo "file $FILES/$IMAGE_FNAME doesn't exists!"
	exit 1
fi

KERNEL=""
RAMDISK=""
DISK_FORMAT=""
CONTAINER_FORMAT=""
case "$IMAGE_FNAME" in
    *.tar.gz|*.tgz)
        # Extract ami and aki files
		# ${IMAGE_FNAME%.tar.gz}表示去掉$IMAGE_FNAME变量末尾的.tar.gz
        [ "${IMAGE_FNAME%.tar.gz}" != "$IMAGE_FNAME" ] &&
            IMAGE_NAME="${IMAGE_FNAME%.tar.gz}" ||
            IMAGE_NAME="${IMAGE_FNAME%.tgz}"
        xdir="$FILES/images/$IMAGE_NAME"
        rm -Rf "$xdir";
        mkdir "$xdir"
        tar -zxf $FILES/$IMAGE_FNAME -C "$xdir"
        KERNEL=$(for f in "$xdir/"*vmlinuz* "$xdir/"aki-*/image; do
                 [ -f "$f" ] && echo "$f" && break; done; true)
        RAMDISK=$(for f in "$xdir/"*initrd* "$xdir/"ari-*/image; do
                 [ -f "$f" ] && echo "$f" && break; done; true)
        IMAGE=$(for f in "$xdir/"*.img "$xdir/"ami-*/image; do
                 [ -f "$f" ] && echo "$f" && break; done; true)
        if [[ -z "$IMAGE_NAME" ]]; then
            IMAGE_NAME=$(basename "$IMAGE" ".img")
        fi
        ;;
    *.img)
        IMAGE="$FILES/$IMAGE_FNAME";
        IMAGE_NAME=$(basename "$IMAGE" ".img")
        DISK_FORMAT=raw
        CONTAINER_FORMAT=bare
        ;;
    *.img.gz)
        IMAGE="$FILES/${IMAGE_FNAME}"
        IMAGE_NAME=$(basename "$IMAGE" ".img.gz")
        DISK_FORMAT=raw
        CONTAINER_FORMAT=bare
        ;;
    *.qcow2)
        IMAGE="$FILES/${IMAGE_FNAME}"
        IMAGE_NAME=$(basename "$IMAGE" ".qcow2")
        DISK_FORMAT=qcow2
        CONTAINER_FORMAT=bare
        ;;
    *) echo "Do not know what to do with $IMAGE_FNAME"; false;;
esac

if [ "$CONTAINER_FORMAT" = "bare" ]; then
	glance image-create --name=$IMAGE_NAME --public --container-format=$CONTAINER_FORMAT --disk-format=$DISK_FORMAT < $IMAGE
	#下面一条语句会让image的状态为queued，应该可以让他变成active，
    #glance --os-auth-token $TOKEN --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME" --public --container-format=$CONTAINER_FORMAT --disk-format $DISK_FORMAT < <(zcat --force "${IMAGE}")
else
    # Use glance client to add the kernel the root filesystem.
    # We parse the results of the first upload to get the glance ID of the
    # kernel for use when uploading the root filesystem.
    KERNEL_ID=""; RAMDISK_ID="";
    if [ -n "$KERNEL" ]; then
        KERNEL_ID=$(glance --os-auth-token $TOKEN --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME-kernel" --public --container-format aki --disk-format aki < "$KERNEL" | grep ' id ' | get_field 2)
    fi
    if [ -n "$RAMDISK" ]; then
        RAMDISK_ID=$(glance --os-auth-token $TOKEN --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME-ramdisk" --public --container-format ari --disk-format ari < "$RAMDISK" | grep ' id ' | get_field 2)
    fi
    glance --os-auth-token $TOKEN --os-image-url http://$GLANCE_HOSTPORT image-create --name "${IMAGE_NAME%.img}" --public --container-format ami --disk-format ami ${KERNEL_ID:+--property kernel_id=$KERNEL_ID} ${RAMDISK_ID:+--property ramdisk_id=$RAMDISK_ID} < "${IMAGE}"
    xdir="$FILES/images/$IMAGE_NAME"
    rm -Rf "$xdir";
fi
